package org.server.task;

import com.alibaba.fastjson.JSON;
import com.iohao.game.action.skeleton.core.CmdInfo;
import com.iohao.game.action.skeleton.core.commumication.BroadcastContext;
import com.iohao.game.bolt.broker.core.client.BrokerClientHelper;
import com.iohao.game.widget.light.timer.task.AbstractTimerTask;
import com.iohao.game.widget.light.timer.task.TimerTaskRegion;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.server.action.ActionCmd;
import org.server.common.BroadcastUtils;
import org.server.common.RedisUtil;
import org.server.domain.Login.MyAttachment;
import org.server.domain.Result.Msg;
import org.server.service.LoginService;
import org.server.service.PokerService;
import org.server.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;

@Slf4j
@Component
@Accessors(chain = true)
public class RoomDealTask extends AbstractTimerTask {

    @Setter
    private PokerService pokerService;
    @Setter
    private List<Long> playerList;
    @Setter
    private String roomName;
    @Setter
    private RedisUtil redisUtil;
    @Setter
    private LoginService loginService;

    @Override
    protected TimerTaskRegion getTimerTaskRegion() {
        return TimerTaskEnum.ROOM_READY;
    }

    @Override
    public void execute() {
        List<List<Integer>> deal = pokerService.deal();
        Iterator<List<Integer>> iterator = deal.iterator();
        for (Long userId : playerList) {
            String poker = JSON.toJSONString(iterator.next());
            CmdInfo cmdInfo = CmdInfo.getCmdInfo(ActionCmd.POKER, ActionCmd.POKER_DEAL);
            BroadcastContext broadcastContext = BrokerClientHelper.me().getBroadcastContext();
            broadcastContext.broadcast(cmdInfo, new Msg(poker), userId);
            redisUtil.setHash(roomName, userId.toString(), poker);
        }

        log.info("开始游戏");
        Long nextOne = Long.valueOf(redisUtil.getValueInHash(roomName, RoomService.CURRENT).toString());
        MyAttachment myAttachment = loginService.getMyAttachment(nextOne);
        String name = myAttachment.getUserNickName();
        //通知玩家
        BroadcastUtils.broadcast(ActionCmd.MSG, ActionCmd.MSG_BROADCAST, new Msg("轮到玩家" + name + "出牌了"), playerList);
        BroadcastUtils.broadcast(ActionCmd.ROOM, ActionCmd.ROOM_TIMER_ON, new Msg(), playerList);
        BroadcastUtils.broadcast(ActionCmd.POKER, ActionCmd.POKER_YOUR_TURN, new Msg(nextOne.toString()), playerList);
        new RoomPlayingTask()
                .setPlayerList(playerList)
                .setRoomName(roomName)
                .setRedisUtil(redisUtil)
                .setLoginService(loginService)
                .setCacheKey(roomName)
                .setDelayExecutionTime(RoomPlayingTask.TURN_TIME)
                .task();
    }
}
